package org.jay.angla.activity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.jay.angla.adapter.SpinArrayAdapter;
import org.jay.angla.onlab.OnlabApplication;
import org.jay.angla.onlab.R;
import org.jay.angla.onlab.R.array;
import org.jay.angla.onlab.R.id;
import org.jay.angla.onlab.R.layout;
import org.jay.angla.onlab.R.string;
import org.jay.angla.utils.Contants;
import org.jay.angla.utils.SharePreferenceUtil;
import org.jay.angla.utils.ToastShow;
import org.jay.angla.utils.Utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

@EActivity(R.layout.activity_qa_setting)
public class QASettingActivity extends Activity {

	public static final int FITTING_METHOD_ONE_ZERO = 0;
	public static final int FITTING_METHOD_ONE = 1;
	public static final int FITTING_METHOD_TWO = 2;
	public static final int FITTING_METHOD_THREE = 3;

	public static final int CONCENTRATION_UNIT_UG_ML = 0;
	public static final int CONCENTRATION_UNIT_MG_ML = 1;
	public static final int CONCENTRATION_UNIT_MG_L = 2;
	public static final int CONCENTRATION_UNIT_G_L = 3;
	public static final int CONCENTRATION_UNIT_mM_L = 4;
	public static final int CONCENTRATION_UNIT_M_L = 5;
	public static final int CONCENTRATION_UNIT_PPM = 6;
	public static final int CONCENTRATION_UNIT_PPB = 7;
	public static final int CONCENTRATION_UNIT_PER = 8;
	public static final int CONCENTRATION_UNIT_IU = 9;

	public static final int WAVELENGTH_ONE = 0;
	public static final int WAVELENGTH_TWO = 1;
	public static final int WAVELENGTH_THREE = 2;

	// ...
	public static final int CALC_TYPE_SAMPLE = 300;
	public static final int CALC_TYPE_FORMALU = 301;

	private Spinner mNiheSpinner;
	private Spinner mNongduSpinner;
	// private Spinner mSampleNumberSpinner;
	private Spinner mWavelengthNumberSpinner;
	private RadioGroup mRadioGroup;
	private RadioButton mStdSampleButton;
	private RadioButton mFormaluCoefflcientButton;

	private EditText mK0EditText;
	private TextView mK0TextView;
	private EditText mK1EditText;
	private TextView mK1TextView;
	private EditText mK2EditText;
	private TextView mK2TextView;
	private EditText mK3EditText;
	private TextView mK3TextView;

	private EditText mWavelength1EditText;
	private EditText mWavelength2EditText;
	private EditText mWavelength3EditText;

	private EditText mRatio1EditText;
	private EditText mRatio2EditText;
	private EditText mRatio3EditText;

	// private TextView mSampleNumberTextView;

	private Button mSureButton;
	private Button mCancelButton;
	private TextView mFormaluDetailTextView;
	// /////////setting//////////
	private int fitting_method;
	private int concentration_uint;
	private int sample_number;
	private int wavelength_number;
	private int calc_type = CALC_TYPE_SAMPLE;
	private float k0;
	private float k1;
	private float k2;
	private float k3;
	private float wavelength1;
	private float wavelength2;
	private float wavelength3;
	private float ratio1;
	private float ratio2;
	private float ratio3;

	public static final int REQUEST_CODE_SURE = 99;
	public static final int REQUEST_CODE_CANCEL = 100;

	private ToastShow mToastShow;

	// /////////setting//////////

	@AfterViews
	void after_ui() {
		mNiheSpinner = (Spinner) findViewById(R.id.sp_nihefangshi);
		mNongduSpinner = (Spinner) findViewById(R.id.sp_nongdudanwei);
		// mSampleNumberSpinner = (Spinner) findViewById(R.id.sp_sample_number);
		mWavelengthNumberSpinner = (Spinner) findViewById(R.id.sp_wavelength_number);
		String[] mStringArray = getResources().getStringArray(
				R.array.nihefangshi);
		ArrayAdapter<String> adapter = new SpinArrayAdapter(this, mStringArray);
		mNiheSpinner.setAdapter(adapter);

		mStringArray = getResources().getStringArray(R.array.nongdudanwei);
		adapter = new SpinArrayAdapter(this, mStringArray);
		mNongduSpinner.setAdapter(adapter);

		mStringArray = getResources().getStringArray(R.array.sample_number);
		adapter = new SpinArrayAdapter(this, mStringArray);
		// mSampleNumberSpinner.setAdapter(adapter);

		mStringArray = getResources().getStringArray(R.array.wavelength_number);
		adapter = new SpinArrayAdapter(this, mStringArray);
		mWavelengthNumberSpinner.setAdapter(adapter);

		mNiheSpinner.setOnItemSelectedListener(new SpinOnItemClickListener());
		mNongduSpinner.setOnItemSelectedListener(new SpinOnItemClickListener());
		// mSampleNumberSpinner
		// .setOnItemSelectedListener(new SpinOnItemClickListener());
		mWavelengthNumberSpinner
				.setOnItemSelectedListener(new SpinOnItemClickListener());

		mRadioGroup = (RadioGroup) findViewById(R.id.rg_qa_seting);
		mStdSampleButton = (RadioButton) findViewById(R.id.rb_std_sample_setting);
		mFormaluCoefflcientButton = (RadioButton) findViewById(R.id.rb_formalu_coefflcient);
		mStdSampleButton.setChecked(true);
		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				int id = group.getCheckedRadioButtonId();
				if (id == R.id.rb_formalu_coefflcient) {
					// set formalu
					// updateFormaluTextView();
					setFormaluEnable(true);
					setSampleEnable(false);
					calc_type = QASettingActivity_.CALC_TYPE_FORMALU;
				} else if (id == R.id.rb_std_sample_setting) {
					setFormaluEnable(false);
					setSampleEnable(true);
					calc_type = QASettingActivity_.CALC_TYPE_SAMPLE;
				}
			}
		});

		mK0EditText = (EditText) findViewById(R.id.et_k0);
		mK0TextView = (TextView) findViewById(R.id.tv_k0);
		mK1EditText = (EditText) findViewById(R.id.et_k1);
		mK1TextView = (TextView) findViewById(R.id.tv_k1);
		mK2EditText = (EditText) findViewById(R.id.et_k2);
		mK2TextView = (TextView) findViewById(R.id.tv_k2);
		mK3EditText = (EditText) findViewById(R.id.et_k3);
		mK3TextView = (TextView) findViewById(R.id.tv_k3);
		mK0EditText.addTextChangedListener(new EditTextDoneListener());
		mK1EditText.addTextChangedListener(new EditTextDoneListener());
		mK2EditText.addTextChangedListener(new EditTextDoneListener());
		mK3EditText.addTextChangedListener(new EditTextDoneListener());

		mWavelength1EditText = (EditText) findViewById(R.id.et_wavelength1);
		mWavelength2EditText = (EditText) findViewById(R.id.et_wavelength2);
		mWavelength3EditText = (EditText) findViewById(R.id.et_wavelength3);
		mRatio1EditText = (EditText) findViewById(R.id.et_ratio1);
		mRatio2EditText = (EditText) findViewById(R.id.et_ratio2);
		mRatio3EditText = (EditText) findViewById(R.id.et_ratio3);
		// mK0EditText.addTextChangedListener(new EditTextWatcher(mK0EditText));
		// mK1EditText.addTextChangedListener(new EditTextWatcher(mK1EditText));
		// mK2EditText.addTextChangedListener(new EditTextWatcher(mK2EditText));
		// mK3EditText.addTextChangedListener(new EditTextWatcher(mK3EditText));
		//
		// mWavelength1EditText.addTextChangedListener(new EditTextWatcher(
		// mWavelength1EditText));
		// mWavelength2EditText.addTextChangedListener(new EditTextWatcher(
		// mWavelength2EditText));
		// mWavelength3EditText.addTextChangedListener(new EditTextWatcher(
		// mWavelength3EditText));

		mFormaluDetailTextView = (TextView) findViewById(R.id.tv_formalu_detail);

		mSureButton = (Button) findViewById(R.id.btn_dialog_ok);
		mSureButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				if ((mK0EditText.getEditableText().toString().length() < 1)
						|| (mK1EditText.getEditableText().toString().length() < 1)
						|| (mK2EditText.getEditableText().toString().length() < 1)
						|| (mK3EditText.getEditableText().toString().length() < 1)
						|| (mWavelength1EditText.getEditableText().toString()
								.length() < 1)
						|| (mWavelength2EditText.getEditableText().toString()
								.length() < 1)
						|| (mWavelength3EditText.getEditableText().toString()
								.length() < 1)
						|| (mRatio1EditText.getEditableText().toString()
								.length() < 1)
						|| (mRatio2EditText.getEditableText().toString()
								.length() < 1)
						|| (mRatio3EditText.getEditableText().toString()
								.length() < 1)

				) {
					mToastShow
							.toastShow(getString(R.string.input_correct_param));
					return;
				}
				k0 = Float.parseFloat(mK0EditText.getEditableText().toString());
				k1 = Float.parseFloat(mK1EditText.getEditableText().toString());
				k2 = Float.parseFloat(mK2EditText.getEditableText().toString());
				k3 = Float.parseFloat(mK3EditText.getEditableText().toString());
				wavelength1 = Float.parseFloat(mWavelength1EditText
						.getEditableText().toString());
				wavelength2 = Float.parseFloat(mWavelength2EditText
						.getEditableText().toString());
				wavelength3 = Float.parseFloat(mWavelength3EditText
						.getEditableText().toString());
				ratio1 = Float.parseFloat(mRatio1EditText.getEditableText()
						.toString());
				ratio2 = Float.parseFloat(mRatio2EditText.getEditableText()
						.toString());
				ratio3 = Float.parseFloat(mRatio3EditText.getEditableText()
						.toString());

				intent.putExtra("FITTING_METHOD", fitting_method);
				intent.putExtra("CONC_UNIT", concentration_uint);
				intent.putExtra("SAMPLE_NUMBER", sample_number);
				intent.putExtra("WAVELENGTH", wavelength_number);
				intent.putExtra("CALC_TYPE", calc_type);
				intent.putExtra("K0", k0);
				intent.putExtra("K1", k1);
				intent.putExtra("K2", k2);
				intent.putExtra("K3", k3);
				intent.putExtra("WAVELENGTH1", wavelength1);
				intent.putExtra("WAVELENGTH2", wavelength2);
				intent.putExtra("WAVELENGTH3", wavelength3);
				setResult(REQUEST_CODE_SURE, intent);
				saveSp();
				finish();
			}
		});
		mCancelButton = (Button) findViewById(R.id.btn_dialog_cancel);
		mCancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setResult(REQUEST_CODE_CANCEL);
				finish();
			}
		});
		// mSampleNumberTextView = (TextView)
		// findViewById(R.id.tv_sample_number);

		setFormaluEnable(false);
		mWavelength2EditText.setEnabled(false);
		mWavelength3EditText.setEnabled(false);
		loadSp();
	}

	private void saveSp() {
		SharePreferenceUtil sp = OnlabApplication.getInstance().getSpUtil();
		sp.setFittingMethod(fitting_method);
		sp.setConcUnit(concentration_uint);
		sp.setSampleNum(sample_number);
		sp.setWavelengthNum(wavelength_number);
		sp.setCalcType(calc_type);
		sp.setK0(k0);
		sp.setK1(k1);
		sp.setK2(k2);
		sp.setK3(k3);
		Log.d(Contants.TAG, "savesp k3 = " + k3);

		sp.setWavelength1(wavelength1);
		sp.setWavelength2(wavelength2);
		sp.setWavelength3(wavelength3);
	}

	private void loadSp() {
		// load sp
		SharePreferenceUtil sp = OnlabApplication.getInstance().getSpUtil();
		fitting_method = sp.getFittingMethod();
		concentration_uint = sp.getConcUnit();
		sample_number = sp.getSampleNum();
		wavelength_number = sp.getWavelengthNum();
		calc_type = sp.getCalcType();
		k0 = sp.getK0();
		k1 = sp.getK1();
		k2 = sp.getK2();
		k3 = sp.getK3();
		Log.d(Contants.TAG, "loadsp k3 = " + k3);
		wavelength1 = sp.getWavelength1();
		wavelength2 = sp.getWavelength2();
		wavelength3 = sp.getWavelength3();

		mNiheSpinner.setSelection(fitting_method);
		mNongduSpinner.setSelection(concentration_uint);
		if (calc_type == CALC_TYPE_SAMPLE) {
			Log.d(Contants.TAG, "sample");
			mStdSampleButton.setChecked(true);
			mFormaluCoefflcientButton.setChecked(false);
			setSampleEnable(true);
			setFormaluEnable(false);
		} else {
			Log.d(Contants.TAG, "formalu");
			mStdSampleButton.setChecked(false);
			mFormaluCoefflcientButton.setChecked(true);
			setSampleEnable(false);
			setFormaluEnable(true);
			updateFittingMethod(fitting_method);
		}
		// mSampleNumberSpinner.setSelection(sample_number - 1);
		mWavelengthNumberSpinner.setSelection(wavelength_number);
		mK0EditText.setText("" + k0);
		mK1EditText.setText("" + k1);
		mK2EditText.setText("" + k2);
		mK3EditText.setText("" + k3);
		Log.d(Contants.TAG, "loadsp k322 = " + k3);
		mWavelength1EditText.setText("" + wavelength1);
		mWavelength2EditText.setText("" + wavelength2);
		mWavelength3EditText.setText("" + wavelength3);
	}

	private void updateFittingMethod(int fit) {
		if (fit == FITTING_METHOD_ONE) {
			mFormaluDetailTextView.setText("CONC = K0 + K1 x A");
			mK0EditText.setVisibility(View.VISIBLE);
			mK0TextView.setVisibility(View.VISIBLE);
			mK1EditText.setVisibility(View.VISIBLE);
			mK1TextView.setVisibility(View.VISIBLE);
			mK2EditText.setVisibility(View.INVISIBLE);
			mK2TextView.setVisibility(View.INVISIBLE);
			mK3EditText.setVisibility(View.INVISIBLE);
			mK3TextView.setVisibility(View.INVISIBLE);
		} else if (fit == FITTING_METHOD_ONE_ZERO) {
			mFormaluDetailTextView.setText("CONC = K1 x A");
			mK0EditText.setVisibility(View.INVISIBLE);
			mK0TextView.setVisibility(View.INVISIBLE);
			mK1EditText.setVisibility(View.VISIBLE);
			mK1TextView.setVisibility(View.VISIBLE);
			mK2EditText.setVisibility(View.INVISIBLE);
			mK2TextView.setVisibility(View.INVISIBLE);
			mK3EditText.setVisibility(View.INVISIBLE);
			mK3TextView.setVisibility(View.INVISIBLE);
		}
	}

	private class SpinOnItemClickListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			// TODO Auto-generated method stub

			// TODO Auto-generated method stub
			Spinner spinner = (Spinner) parent;
			switch (spinner.getId()) {
			case R.id.sp_nihefangshi:
				if (pos == 0) {
					fitting_method = FITTING_METHOD_ONE_ZERO;
				} else if (pos == 1) {
					fitting_method = FITTING_METHOD_ONE;
				} else if (pos == 2) {
					fitting_method = FITTING_METHOD_TWO;
				} else if (pos == 3) {
					fitting_method = FITTING_METHOD_THREE;
				}
				updateFittingMethod(fitting_method);
				break;

			case R.id.sp_nongdudanwei:
				if (pos == 0) {
					concentration_uint = CONCENTRATION_UNIT_UG_ML;
				} else if (pos == 1) {
					concentration_uint = CONCENTRATION_UNIT_MG_ML;
				} else if (pos == 2) {
					concentration_uint = CONCENTRATION_UNIT_MG_L;
				} else if (pos == 3) {
					concentration_uint = CONCENTRATION_UNIT_G_L;
				} else if (pos == 4) {
					concentration_uint = CONCENTRATION_UNIT_mM_L;
				} else if (pos == 5) {
					concentration_uint = CONCENTRATION_UNIT_M_L;
				} else if (pos == 6) {
					concentration_uint = CONCENTRATION_UNIT_PPM;
				} else if (pos == 7) {
					concentration_uint = CONCENTRATION_UNIT_PPB;
				} else if (pos == 8) {
					concentration_uint = CONCENTRATION_UNIT_PER;
				} else if (pos == 9) {
					concentration_uint = CONCENTRATION_UNIT_IU;
				}
				break;

			// case R.id.sp_sample_number:
			// sample_number = pos + 1;
			// break;

			case R.id.sp_wavelength_number:
				if (pos == 0) {
					wavelength_number = WAVELENGTH_ONE;
					mWavelength1EditText.setEnabled(true);
					mRatio1EditText.setEnabled(true);
					mWavelength2EditText.setEnabled(false);
					mRatio2EditText.setEnabled(false);
					mWavelength3EditText.setEnabled(false);
					mRatio3EditText.setEnabled(false);
				} else if (pos == 1) {
					wavelength_number = WAVELENGTH_TWO;
					mWavelength1EditText.setEnabled(true);
					mRatio1EditText.setEnabled(true);
					mWavelength2EditText.setEnabled(true);
					mRatio2EditText.setEnabled(true);
					mWavelength3EditText.setEnabled(false);
					mRatio3EditText.setEnabled(false);
				} else if (pos == 2) {
					wavelength_number = WAVELENGTH_THREE;
					mWavelength1EditText.setEnabled(true);
					mRatio1EditText.setEnabled(true);
					mWavelength2EditText.setEnabled(true);
					mRatio2EditText.setEnabled(true);
					mWavelength3EditText.setEnabled(true);
					mRatio3EditText.setEnabled(true);
				}
				break;
			default:
				break;
			}

		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	class EditTextDoneListener implements TextWatcher {

		private boolean isFirst = true;

		public EditTextDoneListener() {
			isFirst = true;
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (s.toString().length() > 0) {
				if ((mK0EditText.getEditableText().toString().length() < 1)
						|| (mK1EditText.getEditableText().toString().length() < 1)
						|| (mK2EditText.getEditableText().toString().length() < 1)
						|| (mK3EditText.getEditableText().toString().length() < 1)
						|| (mWavelength1EditText.getEditableText().toString()
								.length() < 1)
						|| (mWavelength2EditText.getEditableText().toString()
								.length() < 1)
						|| (mWavelength3EditText.getEditableText().toString()
								.length() < 1)
						|| (mRatio1EditText.getEditableText().toString()
								.length() < 1)
						|| (mRatio2EditText.getEditableText().toString()
								.length() < 1)
						|| (mRatio3EditText.getEditableText().toString()
								.length() < 1)

				) {
					mToastShow
							.toastShow(getString(R.string.input_correct_param));
					return;
				}
				if (isFirst) {
					isFirst = false;
				} else {
					k0 = Float.parseFloat(mK0EditText.getEditableText()
							.toString());
					k1 = Float.parseFloat(mK1EditText.getEditableText()
							.toString());
					k2 = Float.parseFloat(mK2EditText.getEditableText()
							.toString());
					k3 = Float.parseFloat(mK3EditText.getEditableText()
							.toString());
					// updateFormaluTextView();
				}
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

		}

	}

	private void updateFormaluTextView() {
		String showString = "CONC = ";
		float kk0 = Utils.getFloat2(k0);
		float kk1 = Utils.getFloat2(k1);
		float kk2 = Utils.getFloat2(k2);
		float kk3 = Utils.getFloat2(k3);

		if (kk0 != 0) {
			showString += kk0;
		}
		if (kk1 != 0) {
			if (kk0 != 0) {
				showString += " + ";
			}
			showString += kk1 + " x " + "A";
		}
		if (kk2 != 0) {
			if (kk0 != 0 || (kk1 != 0)) {
				showString += " + ";
			}
			showString += kk2 + " x " + "A²";
		}
		if (kk3 != 0) {
			if (kk0 != 0 || (kk1 != 0) || (kk2 != 0)) {
				showString += " + ";
			}
			showString += kk3 + " x " + "A³";
		}

		mFormaluDetailTextView.setText(showString);
	}

	private void setSampleEnable(boolean enable) {
		// mSampleNumberTextView.setEnabled(enable);
		// mSampleNumberSpinner.setEnabled(enable);
	}

	private void setFormaluEnable(boolean enable) {
		mK0EditText.setEnabled(enable);
		mK0TextView.setEnabled(enable);
		mK1EditText.setEnabled(enable);
		mK1TextView.setEnabled(enable);
		mK2EditText.setEnabled(enable);
		mK2TextView.setEnabled(enable);
		mK3EditText.setEnabled(enable);
		mK3TextView.setEnabled(enable);
		mFormaluDetailTextView.setEnabled(enable);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		mToastShow = new ToastShow(this);
	}

	private class EditTextWatcher implements TextWatcher {

		private boolean isChanged = false;
		private EditText mEditText;

		public EditTextWatcher(EditText editText) {
			mEditText = editText;
		}

		@Override
		public void afterTextChanged(Editable editable) {
			// TODO Auto-generated method stub
			if (isChanged) {
				return;
			}
			String str = editable.toString();

			isChanged = true;
			String cuttedStr = str;
			for (int i = str.length() - 1; i >= 0; i--) {
				char c = str.charAt(i);
				if ('.' == c) {
					cuttedStr = str.substring(0, i) + str.substring(i + 1);
					break;
				}
			}
			int NUM = cuttedStr.length();
			int zeroIndex = -1;
			for (int i = 0; i < NUM - 2; i++) {
				char c = cuttedStr.charAt(i);
				if (c != '0') {
					zeroIndex = i;
					break;
				} else if (i == NUM - 3) {
					zeroIndex = i;
					break;
				}
			}
			if (zeroIndex != -1) {
				cuttedStr = cuttedStr.substring(zeroIndex);
			}
			if (cuttedStr.length() < 3) {
				cuttedStr = "0" + cuttedStr;
			}
			cuttedStr = cuttedStr.substring(0, cuttedStr.length() - 2) + "."
					+ cuttedStr.substring(cuttedStr.length() - 2);

			mEditText.setText(cuttedStr);

			mEditText.setSelection(mEditText.length());
			isChanged = false;
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

	}
}
